var express = require('express');
var router = express.Router();
const alipaySdk = require('../utils/alipayConfig');
const axios = require('axios')
const { AlipayFormData } = require('alipay-sdk')
const istoken = require('../utils/token');
const userDataModel = require('../model/userDataModel');
const VipUerModel = require('../model/vipUserModel')
/* 支付 */
router.post('/alipay', istoken, async (req, res, next) => {

  const { id, mail } = req.body
  const userMail = await userDataModel.findOne({ _id: mail })
  const data = await VipUerModel.findOne({ mail: userMail.mail })
  if(data) return res.json({ code: '304', msg:'该账户已是会员' })
  //订单数据
  const bizContent = {
    out_trade_no: id,
    total_amount: '500',
    subject: '开通投放网会员',
    product_code: 'FAST_INSTANT_TRADE_PAY',
  }
  //创建订单
  const result = await alipaySdk.pageExecute('alipay.trade.page.pay', 'GET', { bizContent, returnUrl: 'http://localhost:5173/alipayStatus' });
  res.json({ code: '200', data: result })
});

/* 支付回调-------------------------------------------------- */
router.post('/isAlipay', async (req, res, next) => {
  const { out_trade_no, trade_no, mail } = req.body
  //订单数据
  const bizContent = {
    out_trade_no,
    trade_no
  }
  //发送支付宝axios
  const result = await alipaySdk.pageExecute('alipay.trade.query', 'GET', { bizContent });
  const data = await axios({ url: result, method: "get" })
  const datares = data.data.alipay_trade_query_response
  if (datares.code === '10000') {
    switch (datares.trade_status) {
      case 'TRADE_SUCCESS':
        const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 当前时间 + 5分钟
        const userMail = await userDataModel.findOne({ _id: mail })
        const data = await VipUerModel.findOne({ mail: userMail.mail })
        if (data) return res.json({ code: '200', data: '支付成功' })
        //创建会员
        await VipUerModel.create({ mail: userMail.mail, createdAt: new Date(), expiresAt })
        res.json({ code: '200', data: '支付成功' })
        break;
      case 'TRADE_FINISHED':
        res.json({ code: '200', data: '支付成功,不可退款' })
        break;
      case 'WAIT_BUYER_PAY':
        res.json({ code: '300', data: '等待付款' })
        break;
      case 'TRADE_CLOSED':
        res.json({ code: '404', data: '未付款交易超时关闭' })
        break;
    }
  }
});

module.exports = router;
